// 全局元素
const elements = {
    searchInput: document.getElementById('searchUser'),
    addUserForm: document.getElementById('addUserForm'),
    addUserModal: document.getElementById('addUserModal'),
    editUserForm: document.getElementById('editUserForm'),
    editUserModal: document.getElementById('editUserModal'),
    userTableBody: document.getElementById('userTableBody'),
    startRecord: document.getElementById('startRecord'),
    endRecord: document.getElementById('endRecord'),
    totalRecords: document.getElementById('totalRecords'),
    prevPage: document.getElementById('prevPage'),
    nextPage: document.getElementById('nextPage')
};

// 全局变量存储所有用户数据
let allUsers = [];

// 检查认证状态
async function checkAuth() {
    try {
        const response = await fetch('/api/check_auth', {
            credentials: 'include'
        });

        if (!response.ok) throw new Error('认证检查失败');

        const data = await response.json();

        if (!data.logged_in) {
            window.location.href = '/login';
            return null;
        }

        return {
            id: data.user_id,
            username: data.username,
            type: data.user_type
        };
    } catch (error) {
        console.error('认证检查错误:', error);
        window.location.href = '/login';
        return null;
    }
}

// 检查认证状态并进行适当重定向
async function checkAuthAndRedirect() {
    try {
        const user = await checkAuth();

        if (!user) return;

        // 路径权限验证
        const currentPath = window.location.pathname;
        if (user.type === '管理员' && !currentPath.startsWith('/admin')) {
            window.location.href = '/admin';
            return;
        }

        if (user.type !== '管理员' && currentPath.startsWith('/admin')) {
            window.location.href = '/search';
            return;
        }
    } catch (error) {
        console.error('初始化检查失败:', error);
        window.location.href = '/login';
    }
}

// 搜索用户（修复版）
function searchUsers() {
    const searchTerm = elements.searchInput.value.toLowerCase();

    // 如果搜索词为空，重置搜索
    if (!searchTerm.trim()) {
        resetSearch();
        return;
    }

    let visibleCount = 0;
    const rows = document.querySelectorAll('#userTableBody tr');

    // 隐藏所有行
    rows.forEach(row => {
        row.style.display = 'none';
    });

    // 显示匹配的行
    rows.forEach(row => {
        if (row.classList.contains('no-results-row') || row.classList.contains('loading-row')) {
            return;
        }

        const id = row.cells[0].textContent.toLowerCase();
        const username = row.cells[1].textContent.toLowerCase();
        const email = row.cells[2].textContent.toLowerCase();

        if (id.includes(searchTerm) || username.includes(searchTerm) || email.includes(searchTerm)) {
            row.style.display = '';
            visibleCount++;
        }
    });

    // 如果没有匹配结果，显示提示
    if (visibleCount === 0) {
        // 移除任何现有的"无结果"行
        const existingNoResults = document.querySelector('.no-results-row');
        if (existingNoResults) existingNoResults.remove();

        const noResultsRow = document.createElement('tr');
        noResultsRow.classList.add('no-results-row');
        noResultsRow.innerHTML = `
            <td colspan="5" class="px-6 py-12 text-gray-500">
                <i class="fa fa-search mr-2"></i> 没有找到匹配的用户
            </td>
        `;
        elements.userTableBody.appendChild(noResultsRow);
    }

    // 更新分页信息
    updatePagination(visibleCount, visibleCount);
}

// 重置搜索
function resetSearch() {
    elements.searchInput.value = '';
    renderUserList(allUsers);
    updatePagination(allUsers.length, allUsers.length);
}

// 显示添加用户模态框
document.getElementById('addUserBtn').addEventListener('click', function() {
    elements.addUserModal.style.display = 'flex';
    setTimeout(() => {
        document.getElementById('modalContent').classList.add('active');
    }, 10);
});

// 关闭添加用户模态框
function closeAddUserModal() {
    const modalContent = document.getElementById('modalContent');
    modalContent.classList.remove('active');
    setTimeout(() => {
        elements.addUserModal.style.display = 'none';
        elements.addUserForm.reset();
    }, 300);
}

// 显示编辑用户模态框
function showEditModal(id, username, email, role) {
    document.getElementById('editUserId').value = id;
    document.getElementById('editUsername').value = username;
    document.getElementById('editEmail').value = email;
    document.getElementById('editRole').value = role === '管理员' ? 'admin' : 'user';
    document.getElementById('editUserModal').style.display = 'flex';
}

// 关闭模态框
function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
    if (modalId === 'editUserModal') {
        elements.editUserForm.reset();
    }
}

// 添加用户
async function addUser() {
    const formData = {
        username: elements.addUserForm.newUsername.value,
        email: elements.addUserForm.newEmail.value,
        password: elements.addUserForm.newPassword.value,
        role: elements.addUserForm.newRole.value
    };

    // 简单验证
    if (!formData.username || !formData.email || !formData.password) {
        showToast('请填写所有必填字段', 'error');
        return;
    }

    try {
        showLoading(true);
        const response = await fetch('/api/admin/users', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            credentials: 'include',
            body: JSON.stringify(formData)
        });

        const data = await response.json();

        if (!response.ok) {
            throw new Error(data.message || '添加用户失败');
        }

        closeAddUserModal();
        loadUsers();
        showToast('用户添加成功', 'success');
    } catch (error) {
        console.error('添加用户错误:', error);
        showToast('添加用户失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 更新用户
async function updateUser() {
    const formData = {
        id: elements.editUserForm.editUserId.value,
        username: elements.editUserForm.editUsername.value,
        email: elements.editUserForm.editEmail.value,
        role: elements.editUserForm.editRole.value
    };

    // 只有密码不为空时才更新
    if (elements.editUserForm.editPassword.value) {
        formData.password = elements.editUserForm.editPassword.value;
    }

    // 简单验证
    if (!formData.username || !formData.email) {
        showToast('用户名和邮箱不能为空', 'error');
        return;
    }

    try {
        showLoading(true);
        const response = await fetch(`/api/admin/users/${formData.id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            credentials: 'include',
            body: JSON.stringify(formData)
        });

        const data = await response.json();

        if (!response.ok) {
            throw new Error(data.message || '更新用户失败');
        }

        closeModal('editUserModal');
        loadUsers();
        showToast('用户更新成功', 'success');
    } catch (error) {
        console.error('更新用户错误:', error);
        showToast('更新用户失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 删除用户
async function deleteUser(userId) {
    if (!confirm('确定要删除这个用户吗？此操作不可撤销！')) return;

    try {
        showLoading(true);
        const response = await fetch(`/api/admin/users/${userId}`, {
            method: 'DELETE',
            credentials: 'include'
        });

        const data = await response.json();

        if (!response.ok) {
            throw new Error(data.message || '删除用户失败');
        }

        loadUsers();
        showToast('用户删除成功', 'success');
    } catch (error) {
        console.error('删除用户错误:', error);
        showToast('删除用户失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 显示提示消息
function showToast(message, type = 'info') {
    const toastContainer = document.getElementById('toast-container');
    const toast = document.createElement('div');

    // 设置消息类型样式
    let bgColor, icon;
    switch(type) {
        case 'success':
            bgColor = 'bg-green-500 text-white';
            icon = 'fa-check-circle';
            break;
        case 'error':
            bgColor = 'bg-red-500 text-white';
            icon = 'fa-exclamation-circle';
            break;
        case 'warning':
            bgColor = 'bg-yellow-500 text-white';
            icon = 'fa-exclamation-triangle';
            break;
        default:
            bgColor = 'bg-blue-500 text-white';
            icon = 'fa-info-circle';
    }

    toast.className = `toast-animation toast-shadow fixed py-3 px-5 rounded-lg ${bgColor} z-50 flex items-center`;
    toast.innerHTML = `<i class="fa ${icon} mr-2"></i> ${message}`;

    toastContainer.appendChild(toast);

    // 3秒后自动移除
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => {
            toastContainer.removeChild(toast);
        }, 300);
    }, 3000);
}

// 显示加载状态
function showLoading(show) {
    let loader = document.getElementById('loading-indicator');

    if (show && !loader) {
        loader = document.createElement('div');
        loader.id = 'loading-indicator';
        loader.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        loader.innerHTML = `
            <div class="bg-white p-6 rounded-lg shadow-xl flex items-center">
                <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary mr-3"></div>
                <span class="text-gray-700">加载中...</span>
            </div>
        `;
        document.body.appendChild(loader);
    } else if (!show && loader) {
        document.body.removeChild(loader);
    }
}

// 加载用户列表
async function loadUsers() {
    try {
        showLoading(true);

        const response = await fetch(`/api/admin/users`, {
            credentials: 'include'
        });

        if (!response.ok) throw new Error(`获取用户列表失败: ${response.statusText}`);

        const data = await response.json();

        if (data.success && data.users) {
            allUsers = data.users; // 存储所有用户数据
            renderUserList(allUsers);
            updatePagination(data.users.length, data.users.length);
        } else {
            elements.userTableBody.innerHTML = `
                <tr class="no-results-row">
                    <td colspan="5" class="px-6 py-12 text-gray-500">
                        没有找到用户数据
                    </td>
                </tr>
            `;
            updatePagination(0, 0);
        }
    } catch (error) {
        console.error('加载用户列表错误:', error);
        elements.userTableBody.innerHTML = `
            <tr class="no-results-row">
                <td colspan="5" class="px-6 py-12 text-gray-500">
                    <i class="fa fa-exclamation-circle mr-2"></i> 加载用户数据失败: ${error.message}
                </td>
            </tr>
        `;
        updatePagination(0, 0);
    } finally {
        showLoading(false);
    }
}

// 渲染用户列表
function renderUserList(users) {
    if (!elements.userTableBody) return;

    // 清空表格
    elements.userTableBody.innerHTML = '';

    if (users.length === 0) {
        elements.userTableBody.innerHTML = `
            <tr class="no-results-row">
                <td colspan="5" class="px-6 py-12 text-gray-500">
                    没有找到用户数据
                </td>
            </tr>
        `;
        return;
    }

    users.forEach(user => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.id}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                    <div class="ml-4">
                        <div class="text-sm font-medium text-gray-900">${user.username}</div>
                    </div>
                </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.email}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                    user.type === '管理员' ? 'role-admin' : 'role-user'
                }">
                    ${user.type === '管理员' ? '管理员' : '普通用户'}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium action-buttons">
                <button onclick="showEditModal(${user.id}, '${user.username.replace(/'/g, "\\'")}', '${user.email.replace(/'/g, "\\'")}', '${user.type}')" class="edit-button">
                    <i class="fa fa-edit mr-1"></i> 编辑
                </button>
                <button onclick="deleteUser(${user.id})" class="delete-button">
                    <i class="fa fa-trash mr-1"></i> 删除
                </button>
            </td>
        `;
        elements.userTableBody.appendChild(row);
    });
}

// 更新分页信息
function updatePagination(totalRecords, currentPageSize) {
    if (!elements.totalRecords) return;

    elements.totalRecords.textContent = totalRecords;
    elements.startRecord.textContent = totalRecords > 0 ? 1 : 0;
    elements.endRecord.textContent = currentPageSize;

    // 更新分页按钮状态
    elements.prevPage.disabled = true;
    elements.nextPage.disabled = totalRecords <= currentPageSize;

    // 添加/移除样式类
    elements.prevPage.classList.toggle('opacity-50', elements.prevPage.disabled);
    elements.prevPage.classList.toggle('cursor-not-allowed', elements.prevPage.disabled);
    elements.nextPage.classList.toggle('opacity-50', elements.nextPage.disabled);
    elements.nextPage.classList.toggle('cursor-not-allowed', elements.nextPage.disabled);
}

// 加载上一页
function loadPrevPage() {
    showToast('已经是第一页', 'info');
}

// 加载下一页
function loadNextPage() {
    showToast('已经是最后一页', 'info');
}

// 设置事件监听器
function setupEventListeners() {
    // 搜索功能
    elements.searchInput?.addEventListener('keyup', (e) => {
        if (e.key === 'Enter') searchUsers();
    });

    // 添加用户表单提交
    elements.addUserForm?.addEventListener('submit', function(e) {
        e.preventDefault();
        addUser();
    });

    // 编辑用户表单提交
    elements.editUserForm?.addEventListener('submit', function(e) {
        e.preventDefault();
        updateUser();
    });

    // 点击模态框外部关闭
    elements.addUserModal?.addEventListener('click', function(e) {
        if (e.target === elements.addUserModal) {
            closeAddUserModal();
        }
    });

    document.getElementById('editUserModal')?.addEventListener('click', function(e) {
        if (e.target === this) {
            closeModal('editUserModal');
        }
    });

    // 分页按钮事件
    elements.prevPage?.addEventListener('click', loadPrevPage);
    elements.nextPage?.addEventListener('click', loadNextPage);

    // 退出登录
    document.querySelector('.exit')?.addEventListener('click', logout);
}

// 退出登录
async function logout() {
    try {
        const response = await fetch('/api/logout', {
            method: 'POST',
            credentials: 'include'
        });

        const data = await response.json();

        if (data.redirect) {
            window.location.href = data.redirect;
        }
    } catch (error) {
        console.error('退出登录错误:', error);
        window.location.href = '/login';
    }
}

// 初始化函数
async function init() {
    await checkAuthAndRedirect();
    setupEventListeners();
    loadUsers();
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);

// 全局暴露函数
window.searchUsers = searchUsers;
window.resetSearch = resetSearch;
window.showEditModal = showEditModal;
window.deleteUser = deleteUser;
window.closeModal = closeModal;
window.loadPrevPage = loadPrevPage;
window.loadNextPage = loadNextPage;